package com.unknowpupil.web.interceptor;

import com.unknowpupil.web.exception.MxException;
import com.unknowpupil.web.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Classname: JwtInterceptor
 * @Author: <a> w10g </a>
 * @CreateDate: Create in 2019/10/10 17:19
 * @Description: 扔入容器  组建配置 开启mvc注解支持 试图简析器 释放静态资源 springboot 已经省略 拦截器，简析器 需要自己配置
 * @Version: 1.0
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Resource
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws MxException {
        //
        System.out.println("经过了拦截器");
        String header = request.getHeader("Authorization");
        //如果又包含authorization头信息 就间隙
        if (header != null && !"".equals(header)) {

            if (header.startsWith("Bearer ")) {
                //得到令牌
                String token = header.substring(7);
                try {
                    //简析令牌
                    Claims claims = jwtUtil.parseJWT(token);
                    String roles = (String) claims.get("roles");
                    //如果是admin权限
                    if (roles != null && roles.equals("admin")) {
                        //放入request域中
                        request.setAttribute("claims_admin", token);
                    }
                    if (roles != null && roles.equals("user")) {
                        //放入request域中
                        request.setAttribute("claims_user", token);
                    }

                } catch (Exception e) {
                    throw new MxException("令牌不正确！！！");
                }
            }

            return true;
        }
        //没有token得清空下
        else {
            return  true;
//            throw new MxException("用户未登录，请登陆重试！！！");
        }




    }
}

